package com.example.jnnews;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//1123
public class NewsFragment extends Fragment {
    private RecyclerView recyclerView;
    private ArticleAdapter adapter;
    private List<Article> articles;
    private SharedPreferences sharedPreferences;
    private Gson gson = new Gson();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        sharedPreferences = getActivity().getSharedPreferences("jnnews_prefs", android.content.Context.MODE_PRIVATE);
        loadArticles();
        setupRecyclerView();
        return view;
    }

    private void loadArticles() {
        // 尝试从SharedPreferences加载文章列表
        String json = sharedPreferences.getString("articles", "");
        if (!json.isEmpty()) {
            Type type = new TypeToken<ArrayList<Article>>(){}.getType();
            List<Article> savedArticles = gson.fromJson(json, type);

            // 创建一个新的列表，包含硬编码文章和已保存的文章
            articles = new ArrayList<>(Arrays.asList(
                    new Article("农业科技创新助力乡村振兴",
                            " 近期在京召开的中央经济工作会议，将“坚持不懈抓好‘三农’工作”列为9项重点任务之一。...（此处省略详细内容）", "韩嘉伟"),
                    new Article("绿色种植技术推广成效显著",
                            "我国智慧农业示范区建设取得突破性进展，全国范围内已建成超百万亩高标准智慧农田。...（此处省略详细内容）", "杨玉珍"),
                    new Article("农产品电商发展势头强劲",
                            "一、 行业概况\n\n 农村电商，即农村电子商务，是指利用因特网、计算机等现代信息技术，为从事涉农领域的生产经营主体提供在网上完成产品或服务的销售、购买和电子支付等业务交易的过程。...（此处省略详细内容）", "赵克胜"),
                    new Article("新型农业经营主体培育计划",
                            "农业农村部办公厅关于做好2018年新型职业农民培育工作的通知\n...（此处省略详细内容）", "李斯特")
            ));

            // 将已保存的文章添加到列表中
            articles.addAll(savedArticles);
        } else {
            // 如果没有保存的文章，则仅使用硬编码的文章
            articles = Arrays.asList(
                    new Article("农业科技创新助力乡村振兴",
                            " 近期在京召开的中央经济工作会议，将“坚持不懈抓好‘三农’工作”列为9项重点任务之一。...（此处省略详细内容）", "韩嘉伟"),
                    new Article("绿色种植技术推广成效显著",
                            "我国智慧农业示范区建设取得突破性进展，全国范围内已建成超百万亩高标准智慧农田。...（此处省略详细内容）", "杨玉珍"),
                    new Article("农产品电商发展势头强劲",
                            "一、 行业概况\n\n 农村电商，即农村电子商务，是指利用因特网、计算机等现代信息技术，为从事涉农领域的生产经营主体提供在网上完成产品或服务的销售、购买和电子支付等业务交易的过程。...（此处省略详细内容）", "赵克胜"),
                    new Article("新型农业经营主体培育计划",
                            "农业农村部办公厅关于做好2018年新型职业农民培育工作的通知\n...（此处省略详细内容）", "李斯特")
            );
        }
    }

    private void setupRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new ArticleAdapter(articles, article -> {
            Intent intent = new Intent(getActivity(), ArticleDetailActivity.class);
            intent.putExtra("title", article.getTitle());
            intent.putExtra("content", article.getContent());
            intent.putExtra("author", article.getAuthor());
            intent.putExtra("time", article.getPublishTime().getTime());
            startActivity(intent);
        });
        recyclerView.setAdapter(adapter);
    }

    // 适配器类保持不变
    private static class ArticleAdapter extends RecyclerView.Adapter<ArticleAdapter.ViewHolder> {
        private final List<Article> articles;
        private final OnItemClickListener listener;

        interface OnItemClickListener {
            void onItemClick(Article article);
        }

        ArticleAdapter(List<Article> articles, OnItemClickListener listener) {
            this.articles = articles;
            this.listener = listener;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_article, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            Article article = articles.get(position);
            holder.tvTitle.setText(article.getTitle());
            holder.tvContent.setText(article.getContent());
            holder.itemView.setOnClickListener(v -> listener.onItemClick(article));
        }

        @Override
        public int getItemCount() {
            return articles.size();
        }

        static class ViewHolder extends RecyclerView.ViewHolder {
            TextView tvTitle, tvContent;

            ViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tv_title);
                tvContent = itemView.findViewById(R.id.tv_content);
            }
        }
    }
}